import { handleRouter } from "./handle-router";

let prevRoute = ""; // 上一个路由
let nextRoute = window.location.pathname; // 下一个路由（最新的路由）

export const getPrevRoute = () => prevRoute;
export const getNextRoute = () => nextRoute;

export const rewriteRouter = () => {
  //    - hash: window.onhashchange
  //    - history: window.onpopstate
  //         - history.go, history.back, history.forward 使用 popstate 事件监听
  //         - pushState, replaceState 需要通过函数重写的方式进行劫持
  window.addEventListener("popstate", () => {
    // popstate触发时，路由已经跳转完成了
    prevRoute = nextRoute; // 之前的
    nextRoute = window.location.pathname; // 最新的
    // 处理路由变化
    handleRouter();
  });

  // 保存一份
  const rawPushState = window.history.pushState;
  window.history.pushState = (...args) => {
    // 路由跳转前
    prevRoute = window.location.pathname;
    // 进行路由跳转
    rawPushState.apply(window.history, args);
    // 路由跳转后
    nextRoute = window.location.pathname; 
    handleRouter();
  };

  const rawReplaceState = window.history.replaceState;
  window.history.replaceState = (...args) => {
    prevRoute = window.location.pathname;
    rawReplaceState.apply(window.history, args);
    nextRoute = window.location.pathname; 
    handleRouter();
  };
};
